package com.wongoing.sys.action;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.wongoing.annotation.Description;
import com.wongoing.base.PageResult;
import com.wongoing.sys.action.BaseAction;
import com.wongoing.sys.model.SysBasColumn;
import com.wongoing.sys.model.SysCode;
import com.wongoing.sys.model.SysPermission;
import com.wongoing.sys.model.SysUser;
import com.wongoing.sys.model.ext.SysBasColumnExt;
import com.wongoing.sys.model.ext.SysPermissionExt;
import com.wongoing.sys.service.SysBasColumnService;
import com.wongoing.sys.service.SysCodeService;
import com.wongoing.sys.service.SysUserService;
import com.wongoing.sys.shiro.ShiroUser;
import com.wongoing.sys.viewmodel.JsonResult;
import com.wongoing.util.Constants;
import com.wongoing.util.FileUtil;
import com.wongoing.util.ImageUtil;
import com.wongoing.util.LogService;
import com.wongoing.util.ModelAndViewConstants;
import com.wongoing.util.PageUtil;
import com.wongoing.util.ResourceUtil;
import com.wongoing.util.Status;

@Controller
@RequestMapping("/sys/sysColumnAction")
public class SysBasColumnAction extends BaseAction{
	private SysBasColumnService service;
	private SysUserService sysUserService;
	private SysCodeService sysCodeService;

	@Autowired
	public void setSysCodeService(SysCodeService sysCodeService) {
		this.sysCodeService = sysCodeService;
	}

	@Autowired
	public void setSysUserService(SysUserService sysUserService) {
		this.sysUserService = sysUserService;
	}

	@Autowired
	public void setService(SysBasColumnService service) {
		this.service = service;
	}
	
	/**
	 * 功能说明：进入列表显示界面
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:48:53
	 * @return
	 */
	@RequestMapping(value = "/toList")
	public ModelAndView toList(){
		ModelAndView mv = null;
		try {
			String status = "0";
		
			List<SysBasColumnExt> list = this.service.getColumnListByParam(status);
			List<SysBasColumnExt> result = new ArrayList<SysBasColumnExt>();
			for (SysBasColumnExt speOne : list) {
				if(speOne.getParentId() == null){
					result.add(speOne);
					for (SysBasColumnExt speTwo : list) {
						if(speOne.getId().equals(speTwo.getParentId())){
							result.add(speTwo);
							for (SysBasColumnExt speThree : list) {
								if(speTwo.getId().equals(speThree.getParentId())){
									result.add(speThree);
								}
							}
						}
					}
				}
			}
			mv = new ModelAndView();
			mv.addObject(ModelAndViewConstants.COLUMN_LIST, result);
			mv.setViewName(ModelAndViewConstants.COLUMN_MAIN_VIEW);
			LogService.getInstance(this).debug("获取栏目列表成功："+ModelAndViewConstants.COLUMN_MAIN_VIEW);
		} catch (Exception ex) {
			LogService.getInstance(this).error("获取栏目列表失败：" + ex.getMessage(), ex);
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
		return mv;
	}

	/**
	 * 功能说明：执行栏目名称验证操作
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:48:22
	 * @param op
	 * @param original
	 * @param name
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/doNameValidate")
	public Map<String,Object > doNameValidate(String op,String original,String columnName){
		System.out.println("name的值"+columnName+"op的值"+op+"original的值"+original);
		
		Map<String,Object> jsonResult = null;
		try {
			String where = " BINARY ColumnName = '" + columnName + "' and Status='0'  ";
			List<SysBasColumn> list = this.service.getByWhere(where);
			if(list!=null){
				Integer count = list.size();
				switch (count) {
				case 0:
					jsonResult = JsonResult.jsonValidateReturn(true, "验证通过，该栏目名称可以使用");
					LogService.getInstance(this).debug("该栏目名称验证通过，可使用");
					break;
				case 1:
					if(ModelAndViewConstants.OPERATION_VALUE_EDIT.equals(op)){
						if(columnName.equals(original)){
							jsonResult = JsonResult.jsonValidateReturn(true, "验证通过，该栏目名称可以使用");
							LogService.getInstance(this).debug("该栏目名验证通过，可使用");
						}else{
							jsonResult = JsonResult.jsonValidateReturn(false, "该栏目名称已被使用");
							LogService.getInstance(this).debug("该栏目名称被使用，不可使用");
						}
					}else{
						jsonResult = JsonResult.jsonValidateReturn(false, "该栏目名称已被使用");
						LogService.getInstance(this).debug("该栏目名称已被使用用，不可使用");
					}
					break;
				default:
					jsonResult = JsonResult.jsonValidateReturn(false, "该栏目名称已被使用");
					LogService.getInstance(this).debug("栏目名称已被使用，不可使用");
					break;
				}
			}else{
				jsonResult = JsonResult.jsonValidateReturn(false, "验证失败");
				LogService.getInstance(this).error("栏目名称验证失败");
			}
		} catch (Exception e) {
			jsonResult = JsonResult.jsonValidateReturn(false, "验证失败");
			LogService.getInstance(this).error("栏目名称验证失败");
		}
		return jsonResult;
	}
	/**
	 * 功能说明：进入添加界面
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:49:42
	 * @return
	 */
	@RequestMapping(value = "/toAdd")
	public ModelAndView toAdd(){
		ModelAndView mv = null;
		try {
			String status = "0";

			List<SysBasColumnExt> treeNodes = this.service.getColumnListByParam(status);
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("status", "0");
			 List<SysCode>  code=this.sysCodeService.getByParam(param);
			mv = new ModelAndView();
			mv.addObject(ModelAndViewConstants.OPERATION_KEY, ModelAndViewConstants.OPERATION_VALUE_ADD);
			mv.addObject(ModelAndViewConstants.TITLE_KEY, "添加栏目");
			mv.addObject(ModelAndViewConstants.CODE_MODEL, code);
			mv.addObject(ModelAndViewConstants.TREE_NODES_MODEL, OutputJson(treeNodes));
			mv.setViewName(ModelAndViewConstants.COLUMN_EDIT_VIEW);
			LogService.getInstance(this).debug("进入栏目添加页："+ModelAndViewConstants.COLUMN_EDIT_VIEW);
		} catch (Exception ex) {
			LogService.getInstance(this).error("栏目插入失败：" + ex.getMessage(), ex);
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
		return mv;
	}
	
	/**
	 * 功能说明：进入编辑界面
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:50:12
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/toEdit")
	public ModelAndView toEdit(Integer id){
		ModelAndView mv = null;
		try {
			String status = "0";
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("status", "0");
			 List<SysCode>  code=this.sysCodeService.getByParam(param);
			List<SysBasColumnExt> list = this.service.getColumnListByParam(status);
			SysBasColumn column = this.service.getByPrimaryKey(id);
			List<SysBasColumnExt> treeNodes = new ArrayList<SysBasColumnExt>();
			for (SysBasColumnExt spe : list) {
				spe.setChecked(false);
				if(column.getId().equals(spe.getId())){
					spe.setChecked(true);
				}
				treeNodes.add(spe);
			}
			System.out.println("treeNodes的值"+OutputJson(treeNodes));
			mv = new ModelAndView();
			mv.addObject(ModelAndViewConstants.OPERATION_KEY,ModelAndViewConstants.OPERATION_VALUE_EDIT);
			mv.addObject(ModelAndViewConstants.COLUMN_MODEL, column);
			mv.addObject(ModelAndViewConstants.CODE_MODEL, code);
			mv.addObject(ModelAndViewConstants.TREE_NODES_MODEL, OutputJson(treeNodes));
			mv.addObject(ModelAndViewConstants.TITLE_KEY, "修改栏目");
			mv.setViewName(ModelAndViewConstants.COLUMN_EDIT_VIEW);
			LogService.getInstance(this).debug("进入角色编辑页："+ModelAndViewConstants.COLUMN_EDIT_VIEW);
		} catch (Exception ex) {
			LogService.getInstance(this).error("角色编辑失败：" + ex.getMessage(), ex);
			mv = new ModelAndView(ModelAndViewConstants.ERROR_VIEW);
		}
		return mv;
	}
	/**
	 * 功能说明： 进入删除界面
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:50:32
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/toDel")
	public ModelAndView toDel(Integer id){
		ModelAndView mv = null;
		try {
			mv = new ModelAndView();
			SysBasColumn perm = new SysBasColumn();
			perm.setId(id);
			perm.setStatus(Constants.PERSISTENCE_DELETE_STATUS);
			Map<String,Object> param = new HashMap<String, Object>();
			param.put("status", "0");
			param.put("isUsed", "0");
			//1.查询所有正常状态的栏目
			List<SysBasColumn> all = this.service.getByParam(param);
			param.put("id", id);
			//2.查询选中状态的一条栏目
			List<SysBasColumn> single = this.service.getByParam(param);
			//3.判断该条栏目的等级，如果有下级则收入之，没有则为最下级
			List<SysBasColumn> result = new ArrayList<SysBasColumn>();
			if(single.get(0).getParentId() == null){
				result.add(single.get(0));
				//获取二级目录
				for (SysBasColumn level2 : all) {
					if(single.get(0).getId().equals(level2.getParentId())){
						result.add(level2);
						//获取三级
						for (SysBasColumn level3 : all) {
							if(level2.getId().equals(level3.getParentId())){
								result.add(level3);
							}
						}
					}
				}
			}else{
				//3.2 二级目录判断
				result.add(single.get(0));
				for(SysBasColumn level3 : all){
					//3.3子集目录
					if(single.get(0).getId().equals(level3.getParentId())){
						result.add(level3);
					}
				}
			}
			String str = "";
			for (SysBasColumn s : result) {
				str += s.getId()+",";
			}
			String idStr = str.substring(0, str.length()-1);
			mv.addObject(ModelAndViewConstants.COLUMN_LIST, idStr);
			mv.addObject(ModelAndViewConstants.TITLE_KEY, "栏目删除信息确认");	
			if(result.size()>1){
				mv.addObject(ModelAndViewConstants.CONTENT, single.get(0).getColumnName()+"栏目下有子集，删除该栏目会连同子集一起删除。请确认是否删除？");	
			}else{
				mv.addObject(ModelAndViewConstants.CONTENT, "您要删除'"+single.get(0).getColumnName()+"'栏目吗？确定请点击“确定”按钮删除");
			}
			mv.setViewName(ModelAndViewConstants.COLUMN_DEL_VIEW);
			LogService.getInstance(this).debug("获取栏目删除确认信息成功："+ModelAndViewConstants.COLUMN_DEL_VIEW);
		}catch (Exception e) {
			mv.setViewName(ModelAndViewConstants.ERROR_VIEW);
			LogService.getInstance(this).debug("栏目删除确认信息失败："+ModelAndViewConstants.COLUMN_DEL_VIEW);
		}
		return mv;
	}
	/**
	 * 功能说明：执行删除操作，栏目删除操作，实际调用的update方法
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:51:15
	 * @param idStr
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/doDel")
	public Map<String,Object> doDel(String idStr){
		Map<String, Object> jsonResult = null;
		try {
			String tabid = tabid(ModelAndViewConstants.COLUMN_SYS_ID);
			String[] idStrArr = idStr.split(",");
			List<SysBasColumn> list = new ArrayList<SysBasColumn>();
			for (String id : idStrArr) {
				SysBasColumn sp = new SysBasColumn();
				sp.setId(Integer.parseInt(id));
				sp.setStatus("1");
				
				list.add(sp);
			}
			Integer count = this.service.updateBatch(list);
			if (count > 0) {
				String msg = "栏目删除成功";
				jsonResult = JsonResult.jsonReturn(Status.OK.getCode(), msg,tabid);
				LogService.getInstance(this).debug("删除栏目成功!" + count);
			} else {
				Integer statusCode = 300;
				String msg = "栏目删除失败";
				jsonResult = JsonResult.jsonReturn(statusCode.intValue(), msg, tabid);
				LogService.getInstance(this).debug("删除栏目失败!count-->" + count);
			}
		} catch (Exception e) {
			String msg = "栏目删除失败";
			jsonResult = JsonResult.jsonReturnErr(msg);
			LogService.getInstance(this).debug("删除栏目失败!count-->" + e.getMessage());
		}
		return jsonResult;
	}
	/**
	 * 功能说明：执行保存操作
	 * 修改说明：
	 * @author zhenglibing
	 * @date 2017年10月15日 下午12:51:43
	 * @param entity
	 * @param op
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/doSave")
	public Map<String,Object> doSave(SysBasColumn entity,String op,@RequestParam(value = "file", required = false) MultipartFile file){
		Map<String, Object> jsonResult = null;
		try {
			if (file.getSize() != 0) {
				Map<String, Object> result =  ImageUtil.getInstance().uploadImg(entity.getImageUrl(),Constants.UPLOAD_IMG_COLUMN, file);
				if (result.get("statusCode") =="300") {
					return result;
				}
				entity.setImageUrl((String)result.get("message"));
			}
		
			boolean flag = false;//是否存在下一级的标识量
			Map<String,Object> columnParam = new HashMap<String, Object>();
			columnParam.put("status","0");
			columnParam.put("isUsed","Y");
			List<SysBasColumn> list =  this.service.getByParam(columnParam);//获取所有可用的菜单集合
			List<SysBasColumn> single = new ArrayList<SysBasColumn>();
			if(null == entity.getParentId()){//如果保存菜单没有父级菜单，则直接保存到single集合中
				single.add(entity);
			}else{//如果保存菜单有父级菜单，则获取其父级菜单到single集合中
				columnParam.put("id", entity.getParentId());
				single = this.service.getByParam(columnParam);
			}
			if(list!=null && !list.isEmpty() && single!=null && !single.isEmpty()){
				List<SysBasColumn> level2 = new ArrayList<SysBasColumn>();
				for (SysBasColumn speOne : list) {//遍历出所有二级菜单保存到level2集合中
					if(speOne.getParentId() == null){
						for (SysBasColumn speTwo : list) {
							if(speOne.getId().equals(speTwo.getParentId())){
								level2.add(speTwo);
							}
						}
					}
				}
				if(single.get(0).getParentId()==null){//如果父级菜单没有上级则flag = true
					flag = true;
				}else{
					for (SysBasColumn l2 : level2) {
						if(single.get(0).getId().equals(l2.getId())){
							flag = true;
						}
					}
				}
				//判断父类栏目的等级，若为最小级菜单，则不可在分割
				if(flag){
					//获取当前用户的id
					String tabid = tabid(ModelAndViewConstants.COLUMN_SYS_ID);
					Subject subject = SecurityUtils.getSubject();
					String currentName = subject.getPrincipal().toString();
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("account", currentName);
					List<SysUser> user = this.sysUserService.getByParam(param);
					if(user!=null && !user.isEmpty()){
				
						//添加操作
						if(ModelAndViewConstants.OPERATION_VALUE_ADD.equals(op)){
					
							entity.setRecordTime(new Date());
		
							entity.setStatus("0");
							Integer count = this.service.insert(entity);
							if(count>0){
								Integer statusCode = 200;
								String msg = "栏目添加成功";
								jsonResult = JsonResult.jsonReturn(statusCode.intValue(), msg, tabid);
								LogService.getInstance(this).debug("添加栏目成功!");
							}else{
								String msg = "栏目添加失败";
								jsonResult = JsonResult.jsonReturnErr(msg);
								LogService.getInstance(this).debug("添加栏目失败!count-->"+count);
							}
						}else{
							//修改操作
							Integer count = this.service.updateByPrimaryKey(entity);
							if(count>0){
								Integer statusCode = 200;
								String msg = "栏目修改成功";
								jsonResult = JsonResult.jsonReturn(statusCode.intValue(), msg, tabid);
								LogService.getInstance(this).debug("修改栏目成功!");
							}else{
								String msg = "栏目修改失败";
								jsonResult = JsonResult.jsonReturnErr(msg);
								LogService.getInstance(this).debug("栏目修改失败!count-->"+count);
							}
						}
					}else{
						String msg = "保存栏目信息失败！您登录的当前帐号有问题，请重新登录进行尝试。";
						jsonResult = JsonResult.jsonReturnErr(msg);
						LogService.getInstance(this).debug("保存栏目信息失败！您登录的当前帐号有问题，请重新登录进行尝试。");
					}
				}else{
					jsonResult = JsonResult.jsonReturnErr("'"+entity.getParentName()+"'为最小栏目，不可作为父级栏目！");
					LogService.getInstance(this).debug("'"+entity.getParentName()+"为最小栏目，不可作为父级栏目！");
				}
			}else{
				String tabid = tabid(ModelAndViewConstants.COLUMN_SYS_ID);
				entity.setRecordTime(new Date());
				entity.setStatus("0");
				Integer count = this.service.insert(entity);
				if(count>0){
					Integer statusCode = 200;
					String msg = "栏目添加成功";
					jsonResult = JsonResult.jsonReturn(statusCode.intValue(), msg, tabid);
					LogService.getInstance(this).debug("添加栏目成功!");
				}else{
					String msg = "栏目添加失败";
					jsonResult = JsonResult.jsonReturnErr(msg);
					LogService.getInstance(this).debug("添加栏目失败!count-->"+count);
				}
			}
		} catch (Exception e) {
			String msg = "保存栏目信息失败";
			jsonResult = JsonResult.jsonReturnErr(msg);
			LogService.getInstance(this).debug("保存栏目信息失败!"+e.getMessage());
		}
		return jsonResult;
	}
}
